package com.feihong.yw189.activity.kuandai;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.feihong.yw189.R;
import com.feihong.yw189.activity.base.BaseActivity;
import com.feihong.yw189.activity.kaika.KaiKaActivity;
import com.feihong.yw189.adapter.Kuandai.ZuoJiAdapter;
import com.feihong.yw189.app.App;
import com.feihong.yw189.listener.http.RequestCallBack;
import com.feihong.yw189.message.LoginMessage;
import com.feihong.yw189.model.Kaika.ZuoJiModel;
import com.holenzhou.pullrecyclerview.PullRecyclerView;
import com.holenzhou.pullrecyclerview.layoutmanager.XLinearLayoutManager;

import org.xutils.common.Callback;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


/**
 * 座机号码
 */

public class ZuoJiActivity extends BaseActivity {

    @BindView(R.id.rl_goback)
    RelativeLayout ivBack;
    @BindView(R.id.iv_lin)
    ImageView ivLin;
    @BindView(R.id.txt_pagetitle)
    TextView txtPagetitle;
    @BindView(R.id.et_input)
    EditText minput;
    @BindView(R.id.iv_search)
    ImageView imageView;
    @BindView(R.id.pull_recycler_view)
    PullRecyclerView mPullRecyclerView;

    ZuoJiAdapter mAdapter;
    List<ZuoJiModel.DataBean.ListBean> mDataList;
    int page = 1;
    String getInput;
    Intent mIntent;
    private String acc_type;
    private String segm_id;

    private LinkedHashMap<String, String> mLinkedMap;
    private String direNo;


    @BindView(R.id.connect_net_error_layout)
    LinearLayout mConnectNetErrorLayout;
    @BindView(R.id.null_data_layout)
    RelativeLayout mNullDataLayout;
    @BindView(R.id.null_data_layout_txt)
    TextView mNullDataLayoutTv;
    private int mAllDataSize = 0;

    public static final String SELECT_FIXPHONE_FULL_NUM_KEY = "SELECT_FIXPHONE_FULL_NUM_KEY";
    public static final String SELECT_FIXPHONE_NUM_KEY = "SELECT_FIXPHONE_NUM_KEY";
    public static final String SELECT_FIXPHONE_NUM_ID_KEY = "SELECT_FIXPHONE_NUM_ID_KEY";
    /**
     * 已经选择的固话集合
     */
    public static final String AL_SELECT_FIX_NUM_KEY = "AL_SELECT_FIX_NUM_KEY";
    private ArrayList<String> mSelectFixList;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_listchoose);
        ButterKnife.bind(this);
        mLinkedMap = new LinkedHashMap<>();
        mIntent = getIntent();
        acc_type = mIntent.getStringExtra("acc_type");
        segm_id = mIntent.getStringExtra("segm_id");

        direNo = mIntent.getStringExtra("dire_no");
        mSelectFixList = mIntent.getStringArrayListExtra(AL_SELECT_FIX_NUM_KEY);
        initView();
        initData();
    }

    @Override
    public void setTheme() {

    }

    @Override
    public void onUserLogin(LoginMessage loginMessage) {

    }

    @Override
    protected void onResume() {
        super.onResume();
        hideKey();
    }

    private void hideKey() {

    }

    private void initView() {
        mNullDataLayoutTv.setText("暂无对应的座机号码");
        txtPagetitle.setText("座机号码");
        ivLin.setVisibility(View.GONE);
        minput.setHint("模糊搜索/头尾加*");
        mIntent = new Intent();

    }

    private void noDataLayout() {
        if (mNullDataLayout.getVisibility() == View.GONE) {
            mConnectNetErrorLayout.setVisibility(View.GONE);
            mNullDataLayout.setVisibility(View.VISIBLE);
        }
    }

    private void normalDataLayout() {
        if (mConnectNetErrorLayout.getVisibility() == View.VISIBLE || mNullDataLayout.getVisibility() == View.VISIBLE) {
            mConnectNetErrorLayout.setVisibility(View.GONE);
            mNullDataLayout.setVisibility(View.GONE);
            mPullRecyclerView.setVisibility(View.VISIBLE);
        }
    }

    private void netErrorLayout() {
        if (mConnectNetErrorLayout.getVisibility() == View.GONE) {
            mConnectNetErrorLayout.setVisibility(View.VISIBLE);
            mNullDataLayout.setVisibility(View.GONE);
            mPullRecyclerView.setVisibility(View.GONE);
        }
    }

    private void initData() {
        hideKey();
        mDataList = new ArrayList<>();
        final int page_size = 12;

        getInput = minput.getText().toString().trim();
        // 初始化PullRecyclerView
        mPullRecyclerView.setLayoutManager(new XLinearLayoutManager(this));
        mAdapter = new ZuoJiAdapter(this, R.layout.item_choosezuoji, mDataList);
        mPullRecyclerView.setAdapter(mAdapter);

        mPullRecyclerView.setColorSchemeResources(R.color.appBlue);
        // 设置下拉刷新的旋转圆圈的颜色
        mPullRecyclerView.enablePullRefresh(true);
        // 开启下拉刷新，默认即为true，可不用设置
        mPullRecyclerView.enableLoadDoneTip(false, R.string.load_done_tip);
        // 开启数据全部加载完成时的底部提示，默认为false
        //刷新监听
        mPullRecyclerView.setOnRecyclerRefreshListener(new PullRecyclerView.OnRecyclerRefreshListener() {
            @Override
            public void onPullRefresh() {

                // 下拉刷新网络请求
                mPullRecyclerView.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mAllDataSize = 0;
                        page = 1;
                        mAdapter.clear();
                        //网络请求
                        if (TextUtils.isEmpty(direNo)) {
                            App.getApp().getHttpTools().getZuiji(String.valueOf(page), String.valueOf(page_size), getInput, acc_type, segm_id, callBackUp);
                        } else {
                            App.getApp().getHttpTools().getZuiji_JuXiang(String.valueOf(page), String.valueOf(page_size), getInput, direNo, callBackClick);
                        }
                    }
                }, 300);
            }

            @Override
            public void onLoadMore() {

                // 模拟上拉加载更多网络请求
                mPullRecyclerView.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (TextUtils.isEmpty(direNo)) {
                            App.getApp().getHttpTools().getZuiji(String.valueOf(page), String.valueOf(page_size), getInput, acc_type, segm_id, callBackUp);
                        } else {
                            App.getApp().getHttpTools().getZuiji_JuXiang(String.valueOf(page), String.valueOf(page_size), getInput, direNo, callBackClick);
                        }
                    }
                }, 300);
            }
        });
        mPullRecyclerView.postRefreshing();
        mAdapter.setOnItemClick(new ZuoJiAdapter.FixOnItemClickListener() {
            @Override
            public void onItemClick(ZuoJiModel.DataBean.ListBean listBean) {
                if (listBean == null) {
                    showToast("数据有问题，请选择其他号码");
                    return;
                }
                if (mSelectFixList != null && !mSelectFixList.isEmpty() && mSelectFixList.contains(listBean.getNUMBER_ID())) {
                    showToast("此固话已选择，请选择其他号码");
                    return;
                }
                Intent mIntent = new Intent();
                Bundle bundle = new Bundle();
                bundle.putString(SELECT_FIXPHONE_FULL_NUM_KEY, listBean.getBOROUGH() + "-" + listBean.getNUMBER());
                bundle.putString(SELECT_FIXPHONE_NUM_KEY, listBean.getNUMBER());
                bundle.putString(SELECT_FIXPHONE_NUM_ID_KEY, listBean.getNUMBER_ID());
                mIntent.putExtras(bundle);
                mIntent.setClass(ZuoJiActivity.this, KaiKaActivity.class);
                setResult(Activity.RESULT_OK, mIntent);
                finish();
            }
        });
    }

    @OnClick({R.id.rl_goback, R.id.iv_search, R.id.requery_data_tv})
    public void onViewClicked(View v) {
        switch (v.getId()) {
            case R.id.rl_goback:
                finish();
                break;
            case R.id.iv_search:
                page = 1;
                initData();
                break;
            case R.id.requery_data_tv:
                normalDataLayout();
                mPullRecyclerView.autoRefresh();
                break;
            default:
                break;
        }
    }

    RequestCallBack<String> callBackUp = new RequestCallBack<String>() {
        @Override
        public void onSuccess(String result) {
            try {
                //json解析
                ZuoJiModel zuoJiModelModel = JSON.parseObject(result, ZuoJiModel.class);
                if (zuoJiModelModel != null) {
                    if (zuoJiModelModel.getStatus() == 1) {
                        //list解析
                        List<ZuoJiModel.DataBean.ListBean> mListBean = zuoJiModelModel.getData().getList();
                        if (mListBean == null || mListBean.size() == 0) {
                            if (mAllDataSize == 0) {
                                noDataLayout();
                            }
                            mPullRecyclerView.enableLoadMore(false);
                            return;
                        }
                        int pageSize = mListBean.size();
                        if (pageSize > 0) {
                            ZuoJiModel.DataBean.ListBean model;
                            for (ZuoJiModel.DataBean.ListBean message : zuoJiModelModel.getData().getList()) {
                                model = new ZuoJiModel.DataBean.ListBean();
                                model.setBOROUGH(message.getBOROUGH());
                                model.setNUMBER(message.getNUMBER());
                                model.setNUMBER_ID(message.getNUMBER_ID());
                                model.setRegion((message.getRegion()));
                                mDataList.add(model);
                            }
                            mAllDataSize += pageSize;
                            mAdapter.notifyDataSetChanged();
                            if (pageSize >= 12) {
                                mPullRecyclerView.enableLoadMore(true);
                                page++;
                            } else {
                                mPullRecyclerView.enableLoadMore(false);
                            }
                            normalDataLayout();
                        } else {
                            if (mAllDataSize == 0) {
                                noDataLayout();
                            }
                            mPullRecyclerView.enableLoadMore(false);
                        }
                    } else {
                        if (mAllDataSize > 0) {
                            noDataLayout();
                        }
                        mPullRecyclerView.enableLoadMore(false);
                    }
                } else {
                    if (mAllDataSize > 0) {
                        noDataLayout();
                    }
                    mPullRecyclerView.enableLoadMore(false);
                }
            } catch (Exception ex) {

                mPullRecyclerView.enableLoadMore(false);
            }
        }

        @Override
        public void onError(Throwable ex, boolean isOnCallback) {
            if (activityIsDestory()) {
                return;
            }
            if (mAllDataSize > 0) {
                showToast(getResources().getString(R.string.connect_sever_error_toast));
            } else {
                netErrorLayout();
            }
        }

        @Override
        public void onCancelled(Callback.CancelledException cex) {
        }

        @Override
        public void onFinished() {
            if (activityIsDestory()) {
                return;
            }
            mPullRecyclerView.stopRefresh();
            mPullRecyclerView.stopLoadMore();
        }
    };

    RequestCallBack<String> callBackClick = new RequestCallBack<String>() {
        @Override
        public void onSuccess(String result) {
            try {
                //json解析
                ZuoJiModel zuoJiModelModel = JSON.parseObject(result, ZuoJiModel.class);
                if (zuoJiModelModel != null) {
                    if (zuoJiModelModel.getStatus() == 1) {
                        //list解析
                        int pageSize = zuoJiModelModel.getData().getList().size();
                        if (pageSize > 0) {
                            ZuoJiModel.DataBean.ListBean model;
                            for (ZuoJiModel.DataBean.ListBean message : zuoJiModelModel.getData().getList()) {
                                model = new ZuoJiModel.DataBean.ListBean();
                                model.setBOROUGH(message.getBOROUGH());
                                model.setNUMBER(message.getNUMBER());
                                model.setNUMBER_ID(message.getNUMBER_ID());
                                model.setRegion(message.getRegion());
                                mDataList.add(model);
                            }

                            mAdapter.notifyDataSetChanged();
                            mAllDataSize += pageSize;
                            // mPullRecyclerView.enableLoadMore(page > 0); // 当剩余还有大于0页的数据时，开启上拉加载更多
                            if (pageSize >= 12) {
                                page++;
                                mPullRecyclerView.enableLoadMore(true);
                            } else {
                                mPullRecyclerView.enableLoadMore(false);
                            }
                            normalDataLayout();
                        } else {
                            if (mAllDataSize == 0) {
                                noDataLayout();
                            }
                            mPullRecyclerView.enableLoadMore(false);
                        }
                    } else {
                        if (mAllDataSize == 0) {
                            noDataLayout();
                        }
                        mPullRecyclerView.enableLoadMore(false);
                    }
                } else {
                    if (mAllDataSize == 0) {
                        noDataLayout();
                    }
                    mPullRecyclerView.enableLoadMore(false);
                }
            } catch (Exception ex) {
                mPullRecyclerView.enableLoadMore(false);
            }

        }

        @Override
        public void onError(Throwable ex, boolean isOnCallback) {
            if (activityIsDestory()) {
                return;
            }
            if (mAllDataSize > 0) {
                showToast(getResources().getString(R.string.connect_sever_error_toast));
            } else {
                netErrorLayout();
            }
        }

        @Override
        public void onCancelled(Callback.CancelledException cex) {
        }

        @Override
        public void onFinished() {
            if (activityIsDestory()) {
                return;
            }
            mPullRecyclerView.stopRefresh();
            mPullRecyclerView.stopLoadMore();
        }
    };

}
